/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package relatorios;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperManager;
import net.sf.jasperreports.engine.JasperPrint;

/**
 *
 * @author Vanessinha
 */
@WebServlet(description = "Servlet Chamada de Relatório", urlPatterns = {"/ServletCliente"})
public class ServletCliente extends HttpServlet {

    public ServletCliente() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processaRequisicao(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    private void processaRequisicao(HttpServletRequest req, HttpServletResponse resp) {
        String dataInicio = (String) req.getParameter("dataInicio");
        String dataFim = (String) req.getParameter("dataFim");
        String cliente = req.getParameter("cliente");
        String cmd = req.getParameter("CMD");
        if ("relatorio".equals(cmd)) {
            String driver = "com.mysql.jdbc.Driver";
            String server = "jdbc:mysql://localhost:3306/locadora";
            String user = "root";
            String pass = "mysql";

            try {
                Class.forName(driver);
                Connection conn = DriverManager.getConnection(server, user, pass);
                Map parametros = new HashMap();
                parametros.put("dataInicio", dataInicio);
                parametros.put("dataFim", dataFim);
                parametros.put("cliente", cliente);
                String jasperPath = getServletContext().getRealPath("/WEB-INF/relatorios/") + "/";
                String path = getServletContext().getRealPath("/");
                JasperPrint impressao = JasperFillManager.fillReport(jasperPath + "RelatorioLocacaoClientes.jasper", parametros, conn);
                JasperManager.printReportToPdfFile(impressao, path + "/Relatorio.pdf");
                resp.sendRedirect("Relatorio.pdf");

            } catch (ClassNotFoundException | SQLException | JRException | IOException e) {
            }

        }
    }
}